<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="openDialog(null)">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-select v-model="selectedFilter" @change="handleFilterChange">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" />
        <el-button type="info" @click="query" style="background-color: orange;">查询</el-button>
        <el-button type="info" @click="reset">重置</el-button>
      </div>
      <el-table :empty-text="emptyText" :data="tableData" border class="eltable" @selection-change="handleSelectionChange" height="500px">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index"  label="序号" width="60"></el-table-column>
        <el-table-column prop="pp_id" v-if="false"></el-table-column>
        <el-table-column prop="pp_code" label="品牌编码" ></el-table-column>
        <el-table-column prop="pp_name" label="品牌名称" ></el-table-column>
        <el-table-column prop="pp_jc" label="客商简称" ></el-table-column>
        <el-table-column prop="pp_ywmc" label="英文名称" ></el-table-column>
        <el-table-column v-if="false" prop="pp_ks" label="关联客商"></el-table-column>
        <el-table-column prop="pp_ks_name" label="关联客商" width="565"></el-table-column>
        <el-table-column label="启用" width="70">
          <template #default="{ row }">
            <el-switch v-model="row.pp_state" :active-value="1" :inactive-value="0" @change="updateState(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="text" @click="openDialog(row)">编辑</el-button>
            <el-button type="text" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-row gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌编码：" prop="pp_code">
              <el-input v-model="formData.pp_code"  :readonly="true"  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌名称：" prop="pp_name">
              <el-input v-model="formData.pp_name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌简称：" prop="pp_jc">
              <el-input v-model="formData.pp_jc" placeholder="请输入简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称：" prop="pp_ywmc">
              <el-input v-model="formData.pp_ywmc" placeholder="请输入英文名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="20">
          <el-col :span="24">
            <el-form-item label="关联客户：" prop="pp_ks">
              <!-- 替换为表格 -->
              <el-table :data="ksTableData" border @selection-change="handleKsSelectionChange" height="300px">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="ks_id" label="ID" width="80" />
                <el-table-column prop="ks_code" label="客户编码" v-if="false"/>
                <el-table-column prop="ks_name" label="客户名称" />
                <el-table-column prop="ks_jc" label="客户简称" />
                <el-table-column prop="ks_level_name" label="客户等级" />
                <el-table-column prop="ks_hy_name" label="所属行业" />
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    const emptyText = '暂无数据';
    const selectedFilter = ref('1');
    const searchTable = ref('');
    const tableData = ref([]);
    const multipleSelection = ref([]);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增品牌');
    const formRef = ref(null);
    const formData = ref({
      pp_code: '',
      pp_name: '',
      pp_jc: '',
      pp_ywmc: '',
      pp_ks: '',
    });

    const ksTableData = ref([]); // 关联客商表格数据
    const selectedKs = ref([]); // 选中的关联客商

    // 表单验证：关联客商必须选中至少一个
    const validateSelectedKs = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请至少选择一个关联客商'));
      } else {
        callback();
      }
    };

    const formRules = {
      pp_name: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
      pp_jc: [{ required: true, message: '请输入品牌简称', trigger: 'blur' }],
      pp_ywmc: [{ required: true, message: '请输入英文名称', trigger: 'blur' }],
      pp_ks: [{ required: true, validator: validateSelectedKs }],
    };

    // 获取关联客商数据
    const fetchKsData = () => {
      axios.get('/api/KS/GetOneKS?type=12')
        .then((response) => {
          ksTableData.value = response.data;
        })
        .catch((error) => {
          console.error('获取关联客商数据失败', error);
          ElMessage.error('加载关联客商数据失败，请稍后再试');
        });
    };

    // 处理关联客商表格选中变化
    const handleKsSelectionChange = (val) => {
      selectedKs.value = val;
      // 更新表单数据中的 pp_ks 为选中的 ks_id
      formData.value.pp_ks = val.map((item) => item.ks_id).join(',');
    };

    const fetchTableData = () => {
      axios.get(`/api/PP/GetPP?state=${selectedFilter.value}`)
        .then(res => {
          tableData.value = res.data;
        })
        .catch(err => {
          console.error('Error fetching data:', err);
          ElMessage.error('加载数据失败，请稍后再试');
        });
    };

    // 选中行变化
    const handleSelectionChange = (val) => {
      multipleSelection.value = val;
    };

    // 筛选条件变化
    const handleFilterChange = () => {
      fetchTableData();
    };

    // 更新状态
    const updateState = (row) => {
      ElMessageBox.confirm('改变状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/PP/StateChange?id=${row.pp_id}&state=${row.pp_state}`)
          .then(response => {
            if (response.data === true) {
              ElMessage.success('状态已更新');
            } else {
              ElMessage.error('更新失败，后端返回错误');
            }
            fetchTableData();
          })
          .catch(err => {
            console.error('Error:', err);
            ElMessage.error('更新失败');
          });
      }).catch(() => {
        fetchTableData();
        ElMessage.info('已取消改变');
      });
    };

    // 查询
    const query = () => {
      searchTableData(); // 假设后端支持关键字搜索，需传递searchTable.value
    };

    const searchTableData = () => {
      if (!searchTable.value) {
        fetchTableData();
        return;
      }
      const params = {
        state: selectedFilter.value,
        str: searchTable.value
      };
      axios.get('/api/PP/GetPP', { params })
        .then(res => {
          tableData.value = res.data;
        })
        .catch(err => {
          console.error('Error fetching data:', err);
          ElMessage.error('加载数据失败，请稍后再试');
        });
    };

    // 重置
    const reset = () => {
      searchTable.value = '';
      selectedFilter.value = '1';
      fetchTableData();
    };

    // 删除单行
    const deleteRow = (row) => {
      ElMessageBox.confirm('此操作将删除该列信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/PP/DelPP?id=${row.pp_id}`)
          .then(response => {
            if (response.data === true) {
              ElMessage.success("删除成功");
              fetchTableData();
            } else {
              ElMessage.error("删除失败：后端返回失败");
            }
          })
          .catch(err => {
            console.error('删除失败:', err);
            ElMessage.error("删除失败：请求异常");
          });
      }).catch(() => {
        ElMessage.info("已取消删除");
      });
    };

    const batchDelete = async () => {
      if (multipleSelection.value.length === 0) {
        ElMessage.warning("请先选择要删除的项");
        return;
      }
      try {
        await ElMessageBox.confirm('此操作将删除选中的项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const selectedIds = multipleSelection.value.map(item => item.pp_id); // 确保 pp_id 是后端需要的字段
        const response = await axios.put('/api/PP/DelPPs', selectedIds, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        if (response.data === true) {
          ElMessage.success("批量删除成功");
          fetchTableData();
        } else {
          ElMessage.error("批量删除失败：后端返回失败");
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error("批量删除失败");
        } else {
          ElMessage.info("已取消批量删除");
        }
      }
    };

    const openDialog = async (row) => {
      if (row) {
        formData.value = { ...row };
        dialogTitle.value = '编辑品牌';

        // 根据 pp_ks 的值自动选中表格中的选择框
        if (formData.value.pp_ks) {
          const ksIds = formData.value.pp_ks.split(',').map(id => parseInt(id));
          console.log(ksIds);
          selectedKs.value = ksTableData.value.filter(item => ksIds.includes(item.ks_id));

          // 确保表格数据已加载
          await nextTick(); // 等待 DOM 更新
          ksTableData.value.forEach((item) => {
            const isSelected = ksIds.includes(item.ks_id);
            item._selected = isSelected; // 手动设置选中状态
          });
        }
      } else {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零

        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let code = `PP${formattedTime}${randomNumber}`;

        formData.value = {
          pp_code: code,
          pp_name: '',
          pp_jc: '',
          pp_ywmc: '',
          pp_ks: '',
        };
        dialogTitle.value = '新增品牌';
      }

      dialogVisible.value = true;
    };

    // 提交表单
    const submitForm = async () => {
      try {
        await formRef.value.validate(); // 验证表单
        let response;
        if (formData.value.pp_id) {
          // 编辑模式，调用更新 API
          response = await axios.put('/api/PP/UpdatePP', {
            ...formData.value,
          });
        } else {
          // 新增模式，调用新增 API
          response = await axios.post('/api/PP/AddPP', {
            ...formData.value,
            pp_id: 0, // 新增时 pp_id 设为 0
            pp_state: formData.value.pp_state || 0, // 默认状态
          });
        }
        if (response.data) {
          ElMessage.success(formData.value.pp_id ? '编辑成功' : '新增成功');
          dialogVisible.value = false;
          fetchTableData(); // 刷新表格数据
        } else {
          ElMessage.error('操作失败：后端返回失败');
        }
      } catch (err) {
        console.error('操作失败:', err);
        ElMessage.error('操作失败');
      }
    };

    // 重置表单
    const resetForm = () => {
      formRef.value.resetFields();
      selectedKs.value = [];
      formData.value.pp_ks = '';
    };

    onMounted(() => {
      fetchTableData();
      fetchKsData();
    });

    return {
      searchTableData,
      handleSelectionChange,
      handleFilterChange,
      updateState,
      query,
      reset,
      deleteRow,
      batchDelete,
      emptyText,
      selectedFilter,
      searchTable,
      tableData,
      multipleSelection,
      dialogVisible,
      dialogTitle,
      formRef,
      formData,
      formRules,
      ksTableData,
      selectedKs,
      fetchTableData,
      openDialog,
      submitForm,
      resetForm,
      handleKsSelectionChange,
      validateSelectedKs,
    };
  },
};
</script>

<style scoped>
.container {  
  display: flex;  
  gap: 20px;
  height: 95%;
}  
  
.sidebar {  
  height: 100%;
  
}  
  
.main {  
  width: 80%;
  flex: 1;  
  height: 100%;
}  
  
.header {  
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}  
.eltable{
  height: 95%;
}
.letree{
  height: 100%;
}
.demo-form-inline .el-input {
  --el-input-width: 200px;
}

.demo-form-inline .el-select {
  --el-select-width: 200px;
}
</style>